package cn.edu.sgu.www.mhxysy.service.system.impl;

import cn.edu.sgu.www.mhxysy.consts.RedisKeyPrefixes;
import cn.edu.sgu.www.mhxysy.easyui.component.impl.Tree;
import cn.edu.sgu.www.mhxysy.feign.clients.pms.PmsFeignService;
import cn.edu.sgu.www.mhxysy.redis.RedisUtils;
import cn.edu.sgu.www.mhxysy.restful.JsonResult;
import cn.edu.sgu.www.mhxysy.service.system.MenuService;
import cn.edu.sgu.www.mhxysy.util.UserUtils;
import cn.edu.sgu.www.mhxysy.vo.system.MenuVO;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author 沐雨橙风ιε
 * @version 1.0
 */
@Service
public class MenuServiceImpl implements MenuService {

    @Value("${spring.application.name}")
    public String service;

    private final RedisUtils redisUtils;
    private final PmsFeignService feignService;


    @Autowired
    public MenuServiceImpl(RedisUtils redisUtils, PmsFeignService feignService) {
        this.redisUtils = redisUtils;
        this.feignService = feignService;
    }

    @Override
    @SuppressWarnings("all")
    public List<Tree> getMenuTree() {
        String userId = UserUtils.getUserId();
        String key = RedisKeyPrefixes.PREFIX_USER_MENU_TREE + userId;

        if (redisUtils.hasKey(key)) {
            String data = redisUtils.get(key);

            return JSON.parseArray(data, Tree.class);
        }

        JsonResult<List<Tree>> jsonResult = feignService.getMenuTree(userId);
        List<Tree> menus = null;

        if (jsonResult.isSuccess()) {
            menus = jsonResult.getData();

            String data = JSON.toJSONString(menus);

            redisUtils.set(key, data);
        }

        return menus;
    }

    @Override
    @SuppressWarnings("unchecked")
    public List<MenuVO> getLeftMenu() {
        String userId = UserUtils.getUserId();
        String key = RedisKeyPrefixes.PREFIX_USER_LEFT_MENUS + userId;

        if (redisUtils.hasKey(key)) {
            String data = redisUtils.get(key);

            return JSON.parseObject(data, List.class);
        }

        JsonResult<List<MenuVO>> jsonResult = feignService.getLeftMenu(userId);
        List<MenuVO> menuTrees = null;

        if (jsonResult.isSuccess()) {
            menuTrees = jsonResult.getData();

            redisUtils.set(key, JSON.toJSONString(menuTrees));
        }

        return menuTrees;
    }

}